<?php
/**
 *
 * Author: Lyu
 * Date: 2023/7/22
 * Time: 14:42
 */

namespace App\Model\Core\Admin;

use App\Model\CoreModel;
use App\Service\ParamsService;

class AdminUserRoleModel extends CoreModel
{

    protected string $table = 'admin_user_role';

    /**
     * 获取单条用户信息
     * @param int $role_id
     * @param bool $is_cache
     * @return array
     */
    public function getOne(int $role_id, bool $is_cache = true)
    {
        if ($role_id <= 0) {
            return [];
        }
        return $this->cache($role_id, function () use ($role_id) {
            return obj_to_array($this->getConnectionTable()->where('role_id', $role_id)->first());
        }, $is_cache);
    }

    public function getUsableRoleList($is_cache = true)
    {
        $key = 'usable:';
        return $this->cache($key, function () {
            return obj_to_array($this->getConnectionTable()->where('status', ParamsService::STATUS_ENABLE)->get());
        }, $is_cache);
    }

    /**
     * 添加用户信息
     * @param array $user_data
     * @return bool|int
     */
    public function addOne(array $user_data)
    {
        if (empty($user_data)) {
            return false;
        }
        return $this->getConnectionTable()->insertGetId($user_data);
    }

    /**
     * 更新用户信息
     * @param int $role_id
     * @param array $user_data
     * @return bool
     */
    public function updateOne(int $role_id, array $user_data)
    {
        if ($role_id <= 0 || empty($user_data)) {
            return false;
        }
        $old_info = self::getOne($role_id);
        $res = $this->getConnectionTable()->where('role_id', $role_id)->update($user_data);
        if ($res) {
            self::clearCache($old_info);
        }
        return $res;
    }

    /**
     * 删除角色
     * @param int $role_id
     * @return bool|int
     */
    public function deleteOne(int $role_id)
    {
        if ($role_id <= 0) {
            return false;
        }
        $old_user_info = self::getOne($role_id);
        if (empty($old_user_info)) {
            return false;
        }
        $res = $this->getConnectionTable()->where('role_id', $role_id)->delete();
        if ($res) {
            self::clearCache($old_user_info);
        }
        return $res;
    }


    public function checkName($name, $role_id = 0)
    {
        $query = $this->getConnectionTable()->where('name', $name);
        if ($role_id) {
            $query->where('role_id', '!=', $role_id);
        }
        return obj_to_array($query->first());
    }

    public function getOneByName(string $name)
    {
        if (empty($name)) return [];
        return obj_to_array($this->getConnectionTable()->where('name', $name)->first());
    }

    /**
     * 清空缓存
     * @param array $old_info
     * @return $this
     */
    public function clearCache(array $old_info)
    {
        $cache_k = $old_info['role_id'];
        $this->cleanCache($cache_k);
        $this->cleanCache('usable:');
        return $this;
    }
}
